import asyncRoutes from '@/router/asyncRoutes'
import configRouter from '@/router/constantRoutes'
// import asyncRoutes from '../../router/asyncRoutes'
export default {
  namespaced: true,
  state: {
    asyncRoutes: [], // 根据角色从动态路由表当中筛选出来的路由
    fullRoutes: null
  },
  mutations: {
    set_asyncRoutes (state, params) { // 对应mutation
      state.asyncRoutes = params
    },
    set_fullRoutes (state, params) {
      state.fullRoutes = params
    }
  },
  actions: {
    createRoutes ({ commit }, role) {
      // 根据角色筛选出对应的路由表
      // this.$store.getter
      // console.log('踩踩踩',role.asyncURL);
      // console.log(asyncURL,'啊啊');
      // console.log(asyncRoutes,'哦哦哦');
            // var routes =  hasPermission(asyncRoutes, role.role)

      var routes =  hasPermission(asyncRoutes, role)
      // 存入vuex 记录动态权限路由表
      commit('set_asyncRoutes', routes)
      // 记录完整路由表
      commit('set_fullRoutes', [...routes, ...configRouter])
    }
  }
}
// 递归比较，返回角色对应的动态路由表
function hasPermission (asyncRoutes, role) {
  // console.log(asyncURL);
// 创建一个空的路由表
  var routes = []
  // 遍历动态路由表
  for (var item of asyncRoutes) {
  // 判断如果没有权限就跳过
  // 1、auth不是*号状态
  // 2、且roles不在item的auth清单中
    if (item.meta.auth !== '*' && !item.meta.auth.includes(role)) {
      continue
    }
    // 有权限就提取路由对象
    var route = { ...item }
    // 对 children子路由对象进行递归,如果存在进行递归权限赋值，否则设置为空数组
    route.children = route.children ? hasPermission(route.children, role) : []
    // 将路由对象oush路由表
    routes.push(route)
  }
  // 返回构建好的路由表
  return routes
}
